import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Splash extends StatefulWidget {
  @override
  _SplashState createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  List<Widget> imageList = List();
  String splashKey = 'splash';

  @override
  void initState() {
    super.initState();

    setState(() {
      imageList.add(new Image.asset(
        'lib/images/splash.jpg',
        fit: BoxFit.fill,
      ));
      imageList.add(new Image.asset(
        'lib/images/splash1.jpg',
        fit: BoxFit.fill,
      ));
    });

    SystemChrome.setEnabledSystemUIOverlays([]); //隐藏状态栏
    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);

    getSplash().then((String splashValue) {
      //已经打开过splash不重复打开
      if (splashValue == 'true') {
        Navigator.pushReplacementNamed(
          context,
          '/home',
        );
      }
    });
  }

  @override
  Future<String> getSplash() async {
    String value;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    value = await prefs.getString(splashKey);

    return value;
  }

  Widget build(BuildContext context) {
    return Scaffold(
        body: ConstrainedBox(
            constraints: BoxConstraints.expand(),
            child: Stack(alignment: Alignment.center, children: [
              Container(
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height,
                  child: new Swiper(
                    itemBuilder: (BuildContext context, int index) {
                      return imageList[index];
                    },
                    itemCount: imageList.length,
                    pagination: new SwiperPagination(),
                    onIndexChanged: (index) async {
                      if (index == 0) {
                        //记录已经打开过splash
                        SharedPreferences prefs = await SharedPreferences.getInstance();
                        prefs.setString(splashKey, 'true');

                        //显示状态栏和虚拟按键
                        /*SystemChrome.setEnabledSystemUIOverlays(
                            [SystemUiOverlay.top, SystemUiOverlay.bottom]);*/
                        Navigator.pushReplacementNamed(context, '/home');
                      }
                    },
                  )),
              Positioned(
                  child: Icon(Icons.home, size: 30, color: Colors.white),
                  right: 10,
                  top: 10)
            ])));
  }
}
